package com.inspinia.search.common;

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class EsClient {

    private static TransportClient client = null;

    public EsClient(){}

    private static class SingletonHolder{
        /**
         * 静态初始化器，由JVM来保证线程安全
         */
        private static EsClient instance = new EsClient();
    }

    public static EsClient getInstance(){
        return SingletonHolder.instance;
    }

    /**
     * 获取客户端实例
     * @return
     * @throws UnknownHostException
     */
    public Client getClient(){
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch").build();
        try {
            client = new PreBuiltTransportClient(settings)
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return client;
    }

    /**
     * 关闭客户端
     */
    public void close(){
        client.close();
    }
}
